package tom_io_nio.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

public class AioClient {

    private final AsynchronousSocketChannel client;

    public AioClient() throws Exception{
        //打开客户端
        client = AsynchronousSocketChannel.open();
    }

    public void connect(String host,int port){
        //实现匿名接口，只做写操作
        client.connect(new InetSocketAddress(host, port), null, new CompletionHandler<Void, Object>() {

            @Override
            //实现IO操作完成的方法，//Void什么也不是
            public void completed(Void result, Object attachment) {
                try {
                    client.write(ByteBuffer.wrap(("这是一条测试数据" + System.currentTimeMillis()).getBytes())).get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });

        //下面这段代码是只读数据
        final ByteBuffer bb = ByteBuffer.allocate(1024);
        client.read(bb, null, new CompletionHandler<Integer, Object>() {

            @Override
            public void completed(Integer result, Object attachment) {
                System.out.println("获取反馈结果：" + new String(bb.array()));
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });

        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int count = 10;

        final CountDownLatch latch = new CountDownLatch(10);
        for(int i = 0;i < count; i++){
            latch.countDown();
            new Thread(){
                @Override
                public void run() {
                    try{
                        latch.await();
                        new AioClient().connect("127.0.0.1",8080);
                    }catch(Exception e){

                    }
                }
            }.start();
        }
        Thread.sleep(1000 * 60 * 10);
    }
}
